package com.kusej.gitmanger.form;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.kusej.gitmanger.utils.GitBranchUtils;
import com.kusej.gitmanger.utils.Global;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.lib.Repository;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author kusej
 * 设置
 */
public class MyGitSetDialog extends DialogWrapper {
    private MyGitSetting myGitSetting;
    private final Project project;

    public MyGitSetDialog(@Nullable Project project) {
        super(project, true, IdeModalityType.IDE);
        this.project = project;
        init();
        setTitle("Setting");
        setSize(500, 100);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        myGitSetting = new MyGitSetting(project);
        initComboBoxData();
        return myGitSetting.getContentPanel();
    }

    @Override
    protected void doOKAction() {
        try {
            super.doOKAction();
            PropertiesComponent.getInstance().setValue(Global.username, myGitSetting.getUsername().getText());
            PropertiesComponent.getInstance().setValue(Global.password, myGitSetting.getPassword().getText());
            if (StringUtils.isNotBlank(myGitSetting.getOriginUrl().getText())) {
                GitBranchUtils.saveOriginUri(project.getBasePath(), myGitSetting.getOriginUrl().getText().trim());
            }
            Global.init();
        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }

    }

    private void initComboBoxData() {
        try {
            try (Repository repository = GitBranchUtils.openRepository(project.getBasePath())) {
                String originUrl = repository.getConfig().getString("remote", Global.remoteDefault, "url");
                myGitSetting.getOriginUrl().setText(originUrl);
            }
            myGitSetting.getUsername().setText(PropertiesComponent.getInstance().getValue(Global.username));
            myGitSetting.getPassword().setText(PropertiesComponent.getInstance().getValue(Global.password));

        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }
    }

}
